package com.wzy.oa_sys.controller.file;

import com.aliyun.oss.model.OSSObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wzy.oa_sys.model.pojo.file.OaFile;
import com.wzy.oa_sys.model.response.file.FileResp;
import com.wzy.oa_sys.service.file.FileService;
import com.wzy.oa_sys.util.JwtUtil;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Result;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private FileService fileService;

    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping("/uploadFile")
    public OaFile uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        try {
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);

            // 检查文件类型
            if (!isAllowedFileType(suffix)) {
                throw new RuntimeException("不支持的文件类型");
            }

            OaFile oaFile = new OaFile();
            oaFile.setCFileName(originalFilename);
            oaFile.setCSuffix(suffix);
            oaFile.setNSize(file.getSize());
            oaFile.setDtUploadTime(LocalDateTime.now());
            // 设置当前用户ID，需要从你的认证系统获取
            Long aLong = jwtUtil.extractUserId(request);
            oaFile.setNUserId(aLong);

            return fileService.uploadFile(file, oaFile);
        } catch (Exception e) {
            throw new RuntimeException("文件上传失败: " + e.getMessage());
        }
    }

    private boolean isAllowedFileType(String suffix) {
        suffix = suffix.toLowerCase();
        return suffix.equals("doc") || suffix.equals("docx") ||
                suffix.equals("pdf") || suffix.equals("xls") ||
                suffix.equals("xlsx")|| suffix.equals("ppt")||
                suffix.equals("pptx");
    }

    @GetMapping("/getFileList")
    public List<FileResp> getFileList(HttpServletRequest request) {
        return fileService.fileList();
    }

    @GetMapping("/download/{fileId}")
    public void download(@PathVariable Long fileId, HttpServletResponse response) {
        try {
            // 获取文件信息
            OaFile fileInfo = fileService.getFileById(fileId);
            if (fileInfo == null) {
                throw new RuntimeException("文件不存在");
            }

            // 从OSS获取文件并写入响应
            OSSObject ossObject = fileService.getOssFile(fileInfo.getCFilePath());

            // 设置响应头
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" +
                    URLEncoder.encode(fileInfo.getCFileName(), "UTF-8"));

            // 写入响应
            IOUtils.copy(ossObject.getObjectContent(), response.getOutputStream());
            response.flushBuffer();
        } catch (Exception e) {
            throw new RuntimeException("文件下载失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/{fileId}")
    public ResponseEntity<?> deleteFile(@PathVariable Long fileId) {
        try {
            fileService.deleteFile(fileId);
            return ResponseEntity.ok().body("文件删除成功");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("文件删除失败：" + e.getMessage());
        }
    }

    @GetMapping("/getThreeFiles")
    public List<FileResp> getThreeFiles() {
        return fileService.getThreeFiles();
    }

}
